<template>
  <div class="step-by-step-container">
    <div class="header">
      <h1>逐步硬币算卦</h1>
      <p>请依次抛掷硬币六次，生成完整卦象</p>
    </div>

    <div class="question-section">
      <label for="question">您的问题</label>
      <textarea
        id="question"
        v-model="question"
        placeholder="请输入您想要咨询的问题..."
        rows="3"
      ></textarea>
    </div>

    <div class="coin-section">
      <div class="current-step">
        <p>当前步骤：第 {{ currentStep + 1 }} 次抛掷 (共6次)</p>
      </div>
      
      <div class="coin-result" v-if="yaos.length > 0">
        <h3>当前爻象：</h3>
        <div class="yao-display">
          <div 
            v-for="(yao, index) in yaos" 
            :key="index"
            class="yao-line"
            :class="{
              'yang-yao': yao.value === 7 || yao.value === 9,
              'yin-yao': yao.value === 6 || yao.value === 8,
              'changing': yao.isChanging
            }"
          >
            <div class="yao-number">{{ 6 - index }}爻</div>
          </div>
        </div>
        
        <div class="yao-info">
          <h4>最新抛掷结果：</h4>
          <div class="yao-detail" v-if="yaos.length > 0">
            <p><strong>爻位：</strong>第 {{ 6 - yaos.length + 1 }} 爻</p>
            <p><strong>爻象：</strong>{{ yaos[0].type }}</p>
            <p><strong>解释：</strong>{{ yaos[0].description }}</p>
          </div>
        </div>
      </div>

      <button 
        @click="throwCoins" 
        :disabled="isLoading || currentStep >= 6"
        class="throw-btn"
      >
        {{ currentStep >= 6 ? '已完成六爻' : `抛掷第 ${currentStep + 1} 次` }}
      </button>
    </div>

    <div v-if="currentStep >= 6" class="action-section">
      <button @click="generateGua" class="generate-btn">
        {{ isLoading ? '生成中...' : '生成卦象' }}
      </button>
    </div>



    <InterpretationDisplay 
      v-if="currentStep >= 6 && !isLoading"
      :interpretation="interpretation || yaos.map(yao => yao.description).join('\\n')"
    />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { yijingApi } from '@/api/yijingApi'
import InterpretationDisplay from '@/components/InterpretationDisplay.vue'

const router = useRouter()
const question = ref('')
const currentStep = ref(0)
const yaos = ref([])
const isLoading = ref(false)
const error = ref('')
const interpretation = ref('')

const throwCoins = () => {
  if (currentStep.value >= 6) return
  
  // 模拟抛硬币结果
  const yangCount = Math.floor(Math.random() * 4) // 0-3个阳面
  let yaoValue, isChanging
  
  switch (yangCount) {
    case 3: // 老阳
      yaoValue = 9
      isChanging = true
      break
    case 2: // 少阳
      yaoValue = 7
      isChanging = false
      break
    case 1: // 少阴
      yaoValue = 8
      isChanging = false
      break
    case 0: // 老阴
      yaoValue = 6
      isChanging = true
      break
  }
  
  const yaoType = 
    yaoValue === 6 ? '老阴 (变爻)' :
    yaoValue === 7 ? '少阳' :
    yaoValue === 8 ? '少阴' : '老阳 (变爻)'
  
  yaos.value.unshift({ 
    value: yaoValue, 
    isChanging,
    type: yaoType,
    description: getYaoDescription(yaoValue)
  })
  currentStep.value++
}

const getYaoDescription = (value) => {
  switch(value) {
    case 6: return '三枚硬币皆为反面（阴），为老阴，表示阴气极盛将转阳'
    case 7: return '一枚硬币为正面（阳），为少阳，表示阳气初生'
    case 8: return '两枚硬币为正面（阳），为少阴，表示阴气渐长'
    case 9: return '三枚硬币皆为正面（阳），为老阳，表示阳气极盛将转阴'
    default: return ''
  }
}

const generateGua = async () => {
  if (!question.value.trim()) {
    error.value = '请输入您的问题'
    return
  }

  isLoading.value = true
  error.value = ''

  try {
    const response = await yijingApi.coinDivination({ 
      question: question.value,
      yaos: yaos.value.map(yao => ({
        value: yao.value,
        isChanging: yao.isChanging
      }))
    })
    
    if (response.success && response.data) {
      interpretation.value = response.data.interpretation
      router.push({
        name: 'YijingResult',
        state: { 
          result: {
            ...response.data,
            guaXiang: {
              yaos: yaos.value
            }
          } 
        }
      })
    } else {
      throw new Error(response.message || '生成卦象失败')
    }
  } catch (err) {
    error.value = err.message || '生成卦象时出现错误'
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped>
.step-by-step-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 2rem;
  background: linear-gradient(135deg, #2C1810 0%, #3A2618 50%, #2C1810 100%);
  min-height: 100vh;
  color: #F5DEB3;
}

.header {
  text-align: center;
  margin-bottom: 2rem;
}

.header h1 {
  font-size: 2.5rem;
  color: #D4AF37;
  margin-bottom: 0.5rem;
}

.question-section {
  margin-bottom: 2rem;
}

.question-section label {
  display: block;
  margin-bottom: 0.5rem;
  font-size: 1.1rem;
}

.question-section textarea {
  width: 100%;
  padding: 1rem;
  border: 2px solid #8B4513;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.9);
  color: #2C1810;
  font-size: 1rem;
  min-height: 100px;
}

.coin-section {
  background: rgba(245, 222, 179, 0.95);
  padding: 2rem;
  border-radius: 8px;
  margin-bottom: 2rem;
  text-align: center;
  color: #2C1810;
}

.current-step {
  font-size: 1.2rem;
  margin-bottom: 1.5rem;
}

.yao-display {
  display: flex;
  flex-direction: column-reverse;
  align-items: center;
  gap: 1.5rem;
  margin: 2rem 0;
}

.yao-line {
  position: relative;
  height: 6px;
  margin: 0.5rem 0;
}

.yang-yao {
  width: 120px;
  height: 6px;
  background-color: #D4AF37;
  border-radius: 3px;
}

.yin-yao {
  width: 120px;
  height: 6px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.yin-yao::before,
.yin-yao::after {
  content: '';
  width: 50px;
  height: 6px;
  background-color: #D4AF37;
  border-radius: 3px;
}

.yin-yao::before {
  margin-right: 20px;
}

.yin-yao::after {
  margin-left: 20px;
}

.changing {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

.yao-number {
  position: absolute;
  top: -20px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 12px;
  color: #D4AF37;
  font-weight: bold;
}

.yao-info {
  margin-top: 2rem;
  padding: 1.5rem;
  background: rgba(139, 69, 19, 0.2);
  border-radius: 8px;
  border-left: 4px solid #D4AF37;
}

.yao-info h4 {
  color: #D4AF37;
  margin-bottom: 1rem;
  font-size: 1.1rem;
}

.yao-detail p {
  margin-bottom: 0.5rem;
  line-height: 1.6;
}

.yao-detail strong {
  color: #D4AF37;
  font-weight: bold;
  margin-right: 0.5rem;
}

.throw-btn, .generate-btn {
  padding: 1rem 2rem;
  font-size: 1.1rem;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin: 0.5rem;
}

.throw-btn {
  background: linear-gradient(45deg, #D4AF37, #FFD700);
  color: #2C1810;
}

.throw-btn:hover:not(:disabled) {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(212, 175, 55, 0.4);
}

.generate-btn {
  background: linear-gradient(45deg, #8B4513, #A0522D);
  color: #F5DEB3;
}

.generate-btn:hover:not(:disabled) {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(139, 69, 19, 0.4);
}

button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.error-message {
  color: #ff6b6b;
  text-align: center;
  margin-top: 1rem;
}
</style>